package org.example.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.config.UserContextConfig;
import org.example.service.model.UserModel;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.example.Util.JwtUtil;
import jakarta.servlet.http.Cookie;
/**
 * @author xietl
 * @date 2025/10/8  14:55
 * @description JWT拦截器  * 用于拦截请求并解析JWT Token，将用户信息存入UserContext
 */
@Component
public class Jwtinterceptor implements HandlerInterceptor {
    /**
     * 拦截请求,解析JWT Token,将用户信息存入UserContextConfig
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handler) throws Exception{
        //从请求头获取Token
        String token = request.getHeader("Authorization");
        if(token == null||token.isEmpty()) {
            Cookie[] cookies = request.getCookies();
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    if ("token".equals(cookie.getName())) {
                        token = cookie.getValue();
                        break;
                    }
                }
            }
        }
            if(token==null||token.isEmpty()){
                token = request.getParameter("token");
            }
            if(token!=null&&!token.isEmpty()){
                if(token.startsWith("Bearer ")){
                    token=token.substring(7);
                }
                //验证Token是否有效
                if(JwtUtil.validateToken(token)){
                    UserModel userModel=JwtUtil.getUserFromToken(token);
                    if(userModel!=null){
                        //将用户信息存入UserContext
                        UserContextConfig.setUserModel(userModel);
                    }
                }
            }
            //继续执行后续拦截器和处理器
            return true;
        }

    /**
     * 移除UserContext中的用户信息,
     * 清除UserContext中的信息防止内存泄漏
     */
    @Override
    public void afterCompletion(HttpServletRequest request,HttpServletResponse response,Object handler,Exception ex) throws Exception{
        UserContextConfig.removeUserModel();
        }
    }

